var async = require('async');
var AV = require('leanengine');

//操作产品的模型信息
var Product = AV.Object.extend("Product");
var Seckill = AV.Object.extend("Seckill");
//创建产品信息的查询实例

module.exports = {
    //根据objectId查询单条信息的接口
    get:function(objectId){
        //作为一个promise返回到控制器层面
        var query = new AV.Query(Product);
        return query.get(objectId);
    },
    //根据产品的类型ID来列举产品
    listByClassifyId:function(classifyId,page,limit){
        var query = new AV.Query(Product);
        page = page || 1;
        limit = limit || 100;
        query.skip(limit * (page - 1));
        query.limit(limit);
        query.equalTo('cid',parseInt(classifyId));
        query.equalTo('status',1);
        query.addDescending('isNice');
        query.addDescending('updatedAt');
        //query.descending('isNice');
        return query.find();
    },
    //根据产品的类型ID来列举产品按销量排序
    listByClassifyIdRm:function(classifyId,page,limit){
        var query = new AV.Query(Product);
        page = page || 1;
        limit = limit || 100;
        query.skip(limit * (page - 1));
        query.limit(limit);
        query.equalTo('cid',parseInt(classifyId));
        query.equalTo('status',1);
        query.descending('radix');
        return query.find();
    },
    //根据产品的类型ID来列举产品按价格升序
    listByClassifyIdJg:function(classifyId,page,limit){
        var query = new AV.Query(Product);
        page = page || 1;
        limit = limit || 100;
        query.skip(limit * (page - 1));
        query.limit(limit);
        query.equalTo('cid',parseInt(classifyId));
        query.equalTo('status',1);
        query.ascending('minPrice');
        return query.find();
    },
    getAllLimit:function(page,sort){
        var query = new AV.Query(Product);
        page = page || 1;
        var limit = 10;
        //var limit = limitNum * page;
        query.skip(limit * (page - 1));
        query.limit(limit);
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        if(sort == "rm"){
            query.descending('radix');
        }else if(sort == "jg"){
            query.ascending('minPrice');
        }else{
            query.descending('updatedAt');
        }
        return query.find();
    },
    getAll:function(){
        var query = new AV.Query(Product);
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.descending('updatedAt');
        return query.find();
    },
    getAllRm:function(){
        var query = new AV.Query(Product);
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.descending('radix');
        return query.find();
    },
    getAllJg:function(){
        var query = new AV.Query(Product);
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.ascending('minPrice');
        return query.find();
    },
    /**
     * 搜索商品
     * 可以对商品的名称和简介做一个模糊的匹配搜索
     * @param keyword 关键字
     */
    searchByName:function(keyword){
        var query = new AV.Query(Product);
        query.descending('updatedAt');
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.contains('name',keyword);
        return query.find();
    },
    /**
     * 搜索商品销量排序
     * 可以对商品的名称和简介做一个模糊的匹配搜索
     * @param keyword 关键字
     */
    searchByNameRm:function(keyword){
        var query = new AV.Query(Product);
        query.descending('radix');
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.contains('name',keyword);
        return query.find();
    },
    /**
     * 搜索商品价格升序
     * 可以对商品的名称和简介做一个模糊的匹配搜索
     * @param keyword 关键字
     */
    searchByNameJg:function(keyword){
        var query = new AV.Query(Product);
        query.ascending('minPrice');
        query.equalTo('status',1);
        query.notContainedIn('cid',[10,14,16,17]);
        query.contains('name',keyword);
        return query.find();
    },
    /**
     * 通过产品id获取产品信息
     * @param objectId 产品id
     * @auth James 2015-08-23
     */
    getProDetailByObjId:function(objectId){
        var query = new AV.Query(Product);
        if(objectId){
            return query.get(objectId);
        } else{
            return new AV.Promise.error({code:251});
        }
    },
    /**
     * 更新商品的库存
     * @param pid 产品id
     * @param psid 产品规格id
     * @param updateNum 更新数量
     * @auth James 2015-08-27
     */
    updateInventory:function(pid,psid,updateNum){
        var query = new AV.Query(Product);

        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }

        if(!psid){
            return new AV.Promise.error({code:151});        //产品规格编号不能为空
        }

        if(!updateNum){
            return new AV.Promise.error({code:152});        //更新数量不能为空
        }

        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                //根据产品编号获取该对象
                query.get(pid).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                //获取产品库存
                var spec = res.get('spec');
                var specInfo = spec[psid];
                var inventory = isNaN(specInfo.inventory)?0:specInfo.inventory;
                //新库存
                var newInventory = parseInt(inventory) + parseInt(updateNum);
                //判断新库存是否大于等于0
                if(newInventory >= 0){
                    inventory = newInventory;
                    specInfo['inventory'] = inventory;
                    res.set('spec',spec);
                    res.save().then(function(){
                        callback(null,{code:0,inventory:inventory});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,{code:1,inventory:inventory});  //库存不足
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;

    },
    /**
     * 通过产品和规格id来获取产品的库存
     * @param pid 产品id
     * @param psid 产品规格id
     * @auth James 2015-08-28
     */
    getInventory:function(pid,psid){
        var query = new AV.Query(Product);
        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!psid){
            return new AV.Promise.error({code:151});        //产品规格编号不能为空
        }

        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                //根据产品编号获取该对象
                query.get(pid).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                //获取产品库存
                var spec = res.get('spec');
                var specInfo = spec[psid];
                var inventory = specInfo.inventory;
                //注：inventory 是String 类型
                callback(null,{code:0,inventory:inventory});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    checkIsSeckill:function(pid){
        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                //根据产品编号获取该对象
                var query = new AV.Query(Product);
                query.get(pid).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                var cid = res.get('cid');
                //console.log(cid);
                var query1 = new AV.Query(Seckill);
                query1.equalTo('objectId',cid+'');
                query1.equalTo('status','1');
                query1.first().then(function(info){
                    //console.log('????????????'+info);
                    callback(null, info );
                }).catch(function(err){
                    callback({code:9999,reason:err})
                });
            },
            function(info ,callback){
                //console.log(info.id);
                if(!info || info.length<1 || info=='undefined'){
                    return callback(null ,{code:0,showAccount:true,showAddToCart:true});
                }else{
                    //找到的情况下，记录时间，进行比较。返回结果
                    var beginDate =new Date(info.get('begindate')) ;
                    var endDate =new Date(info.get('enddate')) ;
                    var now =new Date() ;
                    if(beginDate<=now && now<=endDate){
                        return callback(null,{code:0,showAccount:true,showAddToCart:false})
                    }else{
                        return callback(null,{code:0,showAccount:false,showAddToCart:false})
                    }
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //判断商品是否下架
    isOnSale :function(objectid){
        if(!objectid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                //根据产品编号获取该对象
                var query = new AV.Query(Product);
                query.get(objectid).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                if(!res || res==='undefined'){
                    return callback(null, {code:0,isOnSale:false});
                }
                if(res.get('status')===0){
                    return callback(null, {code:0,isOnSale:false});
                }
                callback(null, {code:0,isOnSale:true});
            }

        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    }

};


